/**
 * 公共模块，封装一些公共方法
 */
layui.define(['layer', 'table'], function (exports) {
    var layer = layui.layer;
    var $ = layui.$;

    var pro = {
        isNotBlank: (value) => {
            return value && value.length > 0;
        },
        isBlank: (value) => {
            return !pro.isNotBlank(value);
        },
        /**
         * 设置缓存
         * @param cacheKey
         * @param cacheValue
         */
        setSelectOptionsCache: (cacheKey, cacheValue) => {
            //数据在浏览器中的会话性存储，页面关闭后即失效
            layui.sessionData('_select_options_cache', {key: cacheKey, value: cacheValue});
        },

        /**
         * 读取缓存
         * @param cacheKey
         * @returns cacheValue
         */
        getSelectOptionsCache: (cacheKey) => {
            var cacheValue = layui.sessionData('_select_options_cache');
            return cacheValue?.[cacheKey] || null;
        },
        /** 确认框 */
        confirm: (message) => {
            return new Promise(function (resolve, reject) {
                layer.confirm(message, {
                    btn: ['确认', '取消'],
                    closeBtn: false
                }, function (index) {
                    // 用户点击了确认按钮
                    layer.close(index);
                    resolve();
                }, function () {
                    // 用户点击了取消按钮
                    //reject();
                });
            });
        },

        alertWarn: (msg) => {
            layer.alert(msg, {skin: 'layui-layer-molv', icon: 0});
        },

        alertInfo: (msg) => {
            layer.alert(msg, {skin: 'layui-layer-molv', icon: 1});
        },

        alertError: (msg) => {
            layer.alert(msg, {skin: 'layui-layer-molv', icon: 2});
        },
        ajax: (options, cacheKey) => {
            // 判断缓存
            if (cacheKey) {
                var cacheValue = pro.getSelectOptionsCache(cacheKey);
                if (cacheValue) {
                    return new Promise(function (resolve) {
                        resolve(cacheValue);
                    });
                }
            }
            return new Promise(function (resolve, reject) {
                // 使用 jQuery.ajax 发起请求
                $.ajax(options).done(
                    function (r) {
                        if (r != null && r.status === 0) {
                            if (cacheKey) {
                                pro.setSelectOptionsCache(cacheKey, r);
                            }
                            // 请求成功时，调用 resolve 并传入结果
                            resolve(r);
                        } else {
                            reject(r?.msg || '系统异常');
                        }
                    }
                ).fail(
                    function (error) {
                        // 请求失败时，调用 reject 并传入错误信息
                        reject(error);
                    }
                );
            });
        }
    };
    exports('pro', pro);
});